<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> Qiniu - Upload </title>
    <script src = "./send-data.js"></script>
    <script src = "../upload.js"></script>
    <script src="./init.js"></script>
		<script src="./RongIMLib-2.6.0.js"></script>
		<!-- <script src='//cdn.ronghub.com/RongIMLib-2.5.8.js'></script> -->
   <style type = "text/css">
	.container{
		position: absolute; 
		height: 40px; 
		width: 300px; 
		color: Silver;
    	border-width: 1px; 
    	border-style: Solid;
	}
	.progressBar{
		position: absolute; 
		height: inherit; 
		width: 0%; 
		background-color: gray;
	}

	.progressContent{
		position: absolute; 
		height: inherit; 
		width: 100%;
		text-align:center; 
		font-size:32px;
	}
	#tips{
		float: right;
		width: 60vw;
		background-color: #E5E5E5;
		height: 95vh;
		font-size: 13px;
		overflow: scroll;
	}
	#upload{
		display: none;
		float: left;
	}
	.warn{
		color: red;
	}

</style>
</head>
<body>
	<div id="upload">

		<p><input type="file" id="file-Id" value="upload-file" /></p>
		<div class="container" id="container">
	        <div class = "progressBar" id= "progressBar"></div>
	        <div class = "progressContent" id = "progressContent">
	        </div>
	    </div> 
		
    </div>

    <div id="tips">
    	<span class="warn">
		******************************<br/>
		* 使用融云文件存储注意事项： <br/>
		* 1、有效期为 1 个月<br/>
		* 2、文件不支持迁移<br/>
		******************************<br/>
	</span>
    </div>
	
</body>
<script>

	var getDom = function(id){
		return document.getElementById(id);
	};

    var stringFormat = function(str, vals) {
        for (var i = 0, len = vals.length; i < len; i++) {
            var val = vals[i],
                reg = new RegExp("\\{" + (i) + "\\}", "g");
            str = str.replace(reg, val);
        }
        return str;
    };

	var showResult = function(content, showLine){
		var style = showLine ? '<br/><hr/>' : '<br/>';
		getDom('tips').innerHTML += '<span>'  + content +  '</span>' + style;
	};

	var onConnected = function(im){

		var showLogs = function(title, content, path){
			title && showResult(title);
			content && showResult('&nbsp;&nbsp;' + JSON.stringify(content));
			path = path || '';
			showResult(path, true);
		};

		var createA = function(url){
			var tmpl = '<a href={0} target="_blank">[{1}]</a><br>', str = '';
			url = Object.prototype.toString.call(url) == '[object Array]' ? url : [url];
			for(var i= 0, len = url.length; i < len; i++){
				var item = url[i];
				str += stringFormat(tmpl, [item.url, item.memo]);
			}
			return str;
		};

		var messageItem = {
			file: function(file){
				var name = file.name || '',
				index = name.lastIndexOf('.') + 1,
				type = name.substring(index);

				// 发送文件消息请参考： http://rongcloud.cn/docs/web_api_demo.html#发送消息
				// 创建文件消息
				return new RongIMLib.FileMessage({ name: file.name, size: file.size, type: type, fileUrl: file.downloadUrl});
			},
			image: function(image){
				return new RongIMLib.ImageMessage({content: image.thumbnail, imageUri: image.downloadUrl});
			}
		};
		var createMessage = function(file){

			var msg = messageItem[file.fileType](file);
			var path = createA({ memo:'发送消息', url: 'http://rongcloud.cn/docs/web_api_demo.html#发送消息'});
			showLogs("创建文件消息: ", msg, path);

			var docs = [{ memo:'文件上传', url: 'https://github.com/rongcloud/rongcloud-web-im-upload/tree/master/qiniu'},
						{ memo:'开发指南', url: 'http://rongcloud.cn/docs/web.html'},
						{ memo:'示例文档', url: 'http://rongcloud.cn/docs/web_api_demo.html'},
						{ memo:'示例 Demo', url: 'https://shuise.github.io/tech-research/web-sdk-test/web-sdk-test.html'}];

			var path = createA(docs);
			showLogs('常用文档：', '', path);
		};

		var urlItem = {
			file: function(data){
				var fileType = RongIMLib.FileType.FILE;
				im.getFileUrl(fileType, data.filename, data.name, {
					onSuccess: function(result){
						showLogs("获取文件 URL：", result);
						data.downloadUrl = result.downloadUrl;
						createMessage(data);
					},
					onError: function(error){
						showResult('getFileToken error:' + error);
					}
				}, data, data.uploadMethod);
			},
			image: function(data){
				var fileType = RongIMLib.FileType.IMAGE;
				im.getFileUrl(fileType, data.filename, null, {
					onSuccess: function(result){
						showLogs("获取文件 URL：", result);
						data.downloadUrl = result.downloadUrl;
						createMessage(data);
					},
					onError: function(error){
						showResult('getFileToken error:' + error);
					}
				}, data, data.uploadMethod);
			}
		};
		var getFileUrl = function(data){
			urlItem[data.fileType](data);
		};
		
		var getFileType = function(filename){
			// 默认支持两种图片格式，可自行扩展
			var imageType = {
				'jpg': 1,
				'png': 2
			};
			var index = filename.lastIndexOf('.') + 1,
				type = filename.substring(index);
			return type in imageType ? 'image': 'file';
		};

		var callback = {
			onError	: function (errorCode) { 
				showResult(errorCode);
			},
			onProgress : function (loaded, total) {
				var percent = Math.floor(loaded/total*100);
				var progressBar 	= document.getElementById('progressBar'), 
					progressContent = document.getElementById('progressContent');
					progressBar.style.width = percent + '%';
	        		progressContent.innerHTML = percent + "%";
			},
			onCompleted : function (data) { 
				showLogs("文件上传完成：", data);

				data.fileType = getFileType(data.name);
				getFileUrl(data);
			} 
		};

		// 上传文件
		var file = document.getElementById("file-Id");

		var config = { 
			domain: 'upload.qiniup.com',
			fileType: RongIMLib.FileType.IMAGE,
			getToken: function(callback){
				/****************************
				 * 使用融云文件存储注意事项：
				 * 1、有效期为 1 个月。
				 * 2、文件不可迁移。
				 ****************************
				 */
				im.getFileToken(this.fileType, {
					onSuccess: function(data){
						callback(data.token, data);
					},
					onError: function(error){
						showResult('getFileToken error:' + error);
					}
				});
			}
		};

		var initType = {
			file: function(_file){
				config.fileType = RongIMLib.FileType.FILE;
				UploadClient.initFile(config, function(uploadFile){
					uploadFile.upload(_file, callback);
				});
			},
			image: function(_file){
				UploadClient.initImage(config, function(uploadFile){
					uploadFile.upload(_file, callback);
				});
			}
		};

		file.onchange = function(){
			var _file = this.files[0];
			initType[getFileType(_file.name)](_file);
		};
	};	

	var connect = function(){
		var appkey = '8luwapkvucoil';
		RongIMLib.RongIMClient.init(appkey);

		RongIMLib.RongIMClient.setConnectionStatusListener({
		    onChanged: function (status) {
		        switch (status) {
		            case RongIMLib.ConnectionStatus.CONNECTED:
		                getDom('upload').style.display = 'block';
		                break;
		            }
		    }
		});
		RongIMLib.RongIMClient.setOnReceiveMessageListener({
		    onReceived: function (message) {
		    	showResult(message);
		    }
		});

		var token = '183RX8CR4UcXlV3cANZXnbrkPG6U/xPk3zvPIWf9le0qIwLgOI54+IqjxPVY5a9jZgJ+5WjBf5egVjidhq2Rfg==';
		showResult('connecting');
		RongIMLib.RongIMClient.connect(token, {
	        onSuccess: function(userId) {
	          	showResult("connected." + userId, true);
	          	onConnected(RongIMLib.RongIMClient.getInstance());
	        },
	        onTokenIncorrect: function() {
	          	showResult('token无效');
	        },
	        onError:function(errorCode){
	           	showResult(errorCode);
	        }
		});
	};
	connect();
</script>

</html>